#include"head.h"
#include"funcs.h"

using namespace std;

extern char Vt[] = "some stoping words";
extern char Vn[] = "some not stoping words";
extern map<char, string> First;
extern map<char, string> Last;

map<char, int> axis;
vector<vector<int>> chart;
vector<string>& Ruls;

void fillChart(vector<string>& ruls) {
	Ruls = ruls;
	size_t len = strlen(Vt);

	creatAxis(axis, Vt);
	
	for (size_t i = 0; i < len; i++) {
		char current = Vt[i];
		for (size_t s = 0; s < Ruls.size(); s++) {
			size_t point = 0;
			if (point = inString(Ruls[s].c_str(), current)) {
				if (point != 1) forward(Ruls[s][point - 1], current, point, s);
				if (point != Ruls[s].size() - 1) backward(Ruls[s][point + 1], current, point, s);
			}
		}
	}
}

void forward(char op, char current,size_t point,size_t line) {
	if (inString(Vt, op)) {
		chart[axis[op]][axis[current]] = T_EQU;
		chart[axis[current]][axis[op]] = T_EQU;
	}
	else {
		for (size_t i = 2; point - i > 0; i++) {
			if (inString(Vn, Ruls[line][point - i])) continue;
			chart[axis[current]][axis[Ruls[line][point - i]]] = T_EQU;
			chart[axis[Ruls[line][point - i]]][axis[current]] = T_EQU;
			break;
		}
		for (size_t i = 0; i < Last[op].size(); i++) {
			chart[axis[Last[op][i]]][axis[current]] = T_GRA;
		}
	}
}

void backward(char op, char current, size_t point, size_t line) {
	if (inString(Vt, op)) {
		chart[axis[op]][axis[current]] = T_EQU;
		chart[axis[current]][axis[op]] = T_EQU;
	}
	else {
		for (size_t i = 2; point + i < Ruls[line].size(); i++) {
			if (inString(Vn, Ruls[line][point + i])) continue;
			chart[axis[current]][axis[Ruls[line][point + i]]] = T_EQU;
			chart[axis[Ruls[line][point + i]]][axis[current]] = T_EQU;
			break;
		}
		for (size_t i = 0; i < First[op].size(); i++) {
			chart[axis[current]][axis[Last[op][i]]] = T_LIT;
		}
	}
}

void reduction(string& buf) {
	for (size_t len = 1; len < buf.size(); len++) {
		for (size_t s = 0; s < Ruls.size(); s++) {
			if (Ruls[s].size() == len && Ruls[s].substr(1, Ruls[s].size() - 1).compare(buf.substr(buf.size() - len - 1, len).c_str())) {
				buf = buf.substr(0, buf.size() - len);
				buf.push_back(Ruls[s][0]);
			}
		}
	}
}